package com.wuliu.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.logicalcobwebs.proxool.ProxoolException;
import org.logicalcobwebs.proxool.ProxoolFacade;
import org.logicalcobwebs.proxool.admin.SnapshotIF;

import com.wuliu.util.DbPool;

public final class DbPool {
	private static final Log log = LogFactory.getLog(DbPool.class);
	private static int activeCount;
	public DbPool(){
		
	}
	public static Connection getConnection(){
		
		try {
			Connection conn = DriverManager.getConnection("proxool.conn");
			showSnapshotInfo();
			return conn;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	private static void showSnapshotInfo(){
        try{
            
            SnapshotIF snapshot = ProxoolFacade.getSnapshot("conn", true);
            //获得活动连接数
            int curActiveCount=snapshot.getActiveConnectionCount();
            //获得可得到的连接数
            int availableCount=snapshot.getAvailableConnectionCount();
            //获得总连接数
            int maxCount=snapshot.getMaximumConnectionCount();
            //当活动连接数变化时输出的信息
            if (curActiveCount!=activeCount) {
            	System.out.println("活动连接数"+curActiveCount+"可得到连接数"+availableCount+"总连接数"+maxCount);
                activeCount=curActiveCount;
            }
        }catch(ProxoolException e){
            e.printStackTrace();
        }
	}
	/**
	 * @Title: close
	 * @Description: 释放连接
	 */
	public static final void close(Connection cn, Statement st, ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
			}
		} catch (Throwable e) {
			log.error("ResultSet colsed error:", e);
		}
		try {
			if (st != null) {
				st.close();
			}
		} catch (Throwable e) {
			log.error("Statement colsed error:", e);
		}
		try {
			if (cn != null && !cn.isClosed()) {
				cn.close();
			}
		} catch (Throwable e) {
			log.error("Connection colsed error:", e);
		}
	}

}
